// --------------------------------------------------------------------------
// Constants
// --------------------------------------------------------------------------
const FOXTORRENT_GUID = "{a50b11b9-8495-450d-a90a-0b6be34abe9e}";

// ******************************
// MimeType registration stuff
// ******************************
var gRDF = Components.classes["@mozilla.org/rdf/rdf-service;1"]
                     .getService(Components.interfaces.nsIRDFService);
function HandlerOverride(aURI)
{
  this.URI = aURI;
  this.mUpdateMode = false;
}

HandlerOverride.prototype = {
  get mimeType()
  {
    return getLiteralForContentType(this.URI, "value");
  },
  
  set mimeType(aMIMETypeString)
  {
    changeMIMEStuff(MIME_URI(aMIMETypeString), "value", aMIMETypeString.toLowerCase());
  },
  
  get description()
  {
    return getLiteralForContentType(this.URI, "description");
  },  
  
  set description(aDescriptionString)
  {
    changeMIMEStuff(MIME_URI(this.mimeType), "description", aDescriptionString);
  },
  
  get isEditable()
  {
    return getLiteralForContentType(this.URI, "editable");
  },
  
  set isEditable(aIsEditableString)
  {
    changeMIMEStuff(MIME_URI(this.mimeType), "editable", aIsEditableString);
  },
  
  get largeIconURL()
  {
    var url = getLiteralForContentType(this.URI, "largeIcon");
    if (!url)
      url = "chrome://communicator/skin/content-large.gif";
    return url;
  },
  
  set largeIconURL(aLargeIconURL)
  {
    changeMIMEStuff(MIME_URI(this.mimeType), "largeIcon", aLargeIconURL);
  },
  
  get smallIconURL()
  {
    var url = getLiteralForContentType(this.URI, "smallIcon");
    if (!url)
      url = "chrome://communicator/skin/content-small.gif";
    return url;
  },
  
  set smallIconURL(aSmallIconURL)
  {
    changeMIMEStuff(MIME_URI(this.mimeType), "smallIcon", aSmallIconURL);
  },

  get extensions()
  {
    var extensionResource = gRDF.GetUnicodeResource(NC_RDF("fileExtensions"));
    var contentTypeResource = gRDF.GetUnicodeResource(MIME_URI(this.mimeType));
    var extensionTargets = gDS.GetTargets(contentTypeResource, extensionResource, true);
    var extString = "";
    if (extensionTargets) {
      while (extensionTargets.hasMoreElements()) {
        var currentExtension = extensionTargets.getNext();
        if (currentExtension) {
          currentExtension = currentExtension.QueryInterface(Components.interfaces.nsIRDFLiteral);
          if (extString != "") {
            extString += " ";
          }
          extString += currentExtension.Value.toLowerCase();
        }
      }
    }
    return extString;
  },
  
  addExtension: function (aExtensionString)
  {
    assertMIMEStuff(MIME_URI(this.mimeType), "fileExtensions", aExtensionString.toLowerCase());
  },
  
  removeExtension: function (aExtensionString)
  {
    unassertMIMEStuff(MIME_URI(this.mimeType), "fileExtensions", aExtensionString.toLowerCase());
  },

  clearExtensions: function ()
  {
    var extArray = this.extensions.split(" ");
    for (var i = extArray.length - 1; i >= 0; --i) {
      this.removeExtension(extArray[i]);
    }
  },
  
  get saveToDisk()
  {
    return getHandlerInfoForType(this.URI, "saveToDisk");
  },
  
  set saveToDisk(aSavedToDisk)
  {
    changeMIMEStuff(HANDLER_URI(this.mimeType), "saveToDisk", aSavedToDisk);
    this.setHandlerProcedure("handleInternal", "false");
    this.setHandlerProcedure("useSystemDefault", "false");
 },

  get useSystemDefault()
  {
    return getHandlerInfoForType(this.URI, "useSystemDefault");
  },

  set useSystemDefault(aUseSystemDefault)
  {
    changeMIMEStuff(HANDLER_URI(this.mimeType), "useSystemDefault", aUseSystemDefault);
    this.setHandlerProcedure("handleInternal", "false");
    this.setHandlerProcedure("saveToDisk", "false");
  },
  
  get handleInternal()
  {
    return getHandlerInfoForType(this.URI, "handleInternal");
  },
  
  set handleInternal(aHandledInternally)
  {
    changeMIMEStuff(HANDLER_URI(this.mimeType), "handleInternal", aHandledInternally);
    this.setHandlerProcedure("saveToDisk", "false");
    this.setHandlerProcedure("useSystemDefault", "false");
  },

  setHandlerProcedure: function (aHandlerProcedure, aValue)
  {
    var handlerSource = gRDF.GetUnicodeResource(HANDLER_URI(this.mimeType));
    var handlerProperty = gRDF.GetUnicodeResource(NC_RDF(aHandlerProcedure));
    var oppositeValue = aValue == "false" ? "true" : "false";
    var trueLiteral = gRDF.GetLiteral(oppositeValue);
    var hasCounterpart = gDS.HasAssertion(handlerSource, handlerProperty, trueLiteral, true);
    if (hasCounterpart) {
      var falseLiteral = gRDF.GetLiteral(aValue);
      gDS.Change(handlerSource, handlerProperty, trueLiteral, falseLiteral);
    }
  },
  
  get alwaysAsk()
  {
    return getHandlerInfoForType(this.URI, "alwaysAsk");
  },
  
  set alwaysAsk(aAlwaysAsk)
  {
    changeMIMEStuff(HANDLER_URI(this.mimeType), "alwaysAsk", aAlwaysAsk);
  },
  
  get appDisplayName()
  {
    return getHelperAppInfoForType(this.URI, "prettyName");
  },
  
  set appDisplayName(aDisplayName)
  {
    changeMIMEStuff(APP_URI(this.mimeType), "prettyName", aDisplayName);
  },
  
  get appPath()
  {
    return getHelperAppInfoForType(this.URI, "path");
  },
  
  set appPath(aAppPath)
  {
    changeMIMEStuff(APP_URI(this.mimeType), "path", aAppPath);
  },

  buildLinks: function()
  {
    // assert the handler resource
    var mimeSource = gRDF.GetUnicodeResource(MIME_URI(this.mimeType));
    var handlerProperty = gRDF.GetUnicodeResource(NC_RDF("handlerProp"));
    var handlerResource = gRDF.GetUnicodeResource(HANDLER_URI(this.mimeType));
    gDS.Assert(mimeSource, handlerProperty, handlerResource, true);

    // assert the helper app resource
    var helperAppProperty = gRDF.GetUnicodeResource(NC_RDF("externalApplication"));
    var helperAppResource = gRDF.GetUnicodeResource(APP_URI(this.mimeType));
    gDS.Assert(handlerResource, helperAppProperty, helperAppResource, true);

    // add the mime type to the MIME types seq
    var container = Components.classes["@mozilla.org/rdf/container;1"].createInstance();
	try
	{
    if (container) {
      container = container.QueryInterface(Components.interfaces.nsIRDFContainer);
      if (container) {
        var containerRes = gRDF.GetUnicodeResource("urn:mimetypes:root");
        container.Init(gDS, containerRes);
        var element = gRDF.GetUnicodeResource(MIME_URI(this.mimeType));
        if (container.IndexOf(element) == -1)
          container.AppendElement(element);
      }
    }
	}
	catch(e) { }
  }
 
};

function NC_RDF(aProperty)
{
  return "http://home.netscape.com/NC-rdf#" + aProperty;
}

function HANDLER_URI(aHandler)
{
  return "urn:mimetype:handler:" + aHandler;
}

function APP_URI(aType)
{
  return "urn:mimetype:externalApplication:" + aType;
}

function MIME_URI(aType)
{
  return "urn:mimetype:" + aType;
}

function getLiteralForContentType(aURI, aProperty)
{
  var contentTypeResource = gRDF.GetUnicodeResource(aURI);
  var propertyResource = gRDF.GetUnicodeResource(NC_RDF(aProperty));
  return getLiteral(contentTypeResource, propertyResource);
}

function getLiteral(aSource, aProperty)
{
  var node = gDS.GetTarget(aSource, aProperty, true);
  if (node) {
    node = node.QueryInterface(Components.interfaces.nsIRDFLiteral);
    return node.Value;
  }
  return "";
}

function getHandlerInfoForType(aURI, aPropertyString)
{
  // get current selected type
  var handler = HANDLER_URI(getLiteralForContentType(aURI, "value"));
  var source = gRDF.GetUnicodeResource(handler);
  var property = gRDF.GetUnicodeResource(NC_RDF(aPropertyString));
  var target = gDS.GetTarget(source, property, true);
  if (target) {
    target = target.QueryInterface(Components.interfaces.nsIRDFLiteral);
    return target.Value;
  }
  return "";
}

function getHelperAppInfoForType(aURI, aPropertyString)
{
  var appURI      = APP_URI(getLiteralForContentType(aURI, "value"));
  var appRes      = gRDF.GetUnicodeResource(appURI);
  var appProperty = gRDF.GetUnicodeResource(NC_RDF(aPropertyString));
  return getLiteral(appRes, appProperty);
}

function mimeHandlerExists(aMIMEType)
{
  var valueProperty = gRDF.GetUnicodeResource(NC_RDF("value"));
  var mimeSource = gRDF.GetUnicodeResource(MIME_URI(aMIMEType));
  var mimeLiteral = gRDF.GetLiteral(aMIMEType);
  return gDS.HasAssertion(mimeSource, valueProperty, mimeLiteral, true);
}

function assertMIMEStuff(aMIMEString, aPropertyString, aValueString)
{
  var mimeSource = gRDF.GetUnicodeResource(aMIMEString);
  var valueProperty = gRDF.GetUnicodeResource(NC_RDF(aPropertyString));
  var mimeLiteral = gRDF.GetLiteral(aValueString);
  gDS.Assert(mimeSource, valueProperty, mimeLiteral, true);
}

function changeMIMEStuff(aMIMEString, aPropertyString, aValueString)
{
  var mimeSource = gRDF.GetUnicodeResource(aMIMEString);
  var valueProperty = gRDF.GetUnicodeResource(NC_RDF(aPropertyString));
  var mimeLiteral = gRDF.GetLiteral(aValueString);
  var currentValue = gDS.GetTarget(mimeSource, valueProperty, true);
  if (currentValue) {
    gDS.Change(mimeSource, valueProperty, currentValue, mimeLiteral);
  } else {
    gDS.Assert(mimeSource, valueProperty, mimeLiteral, true);
  } 
}

function unassertMIMEStuff(aMIMEString, aPropertyString, aValueString)
{
  var mimeSource = gRDF.GetUnicodeResource(aMIMEString);
  var valueProperty = gRDF.GetUnicodeResource(NC_RDF(aPropertyString));
  var mimeLiteral = gRDF.GetLiteral(aValueString);
  gDS.Unassert(mimeSource, valueProperty, mimeLiteral, true);
}

function removeOverride(aMIMEType)
{
  // remove entry
  var rdfc = Components.classes["@mozilla.org/rdf/container;1"].createInstance();
  if (rdfc) {
    rdfc = rdfc.QueryInterface(Components.interfaces.nsIRDFContainer);
    if (rdfc) {
      var containerRes = gRDF.GetUnicodeResource("urn:mimetypes:root");
      rdfc.Init(gDS, containerRes);
      var element = gRDF.GetUnicodeResource(MIME_URI(aMIMEType));
      if (rdfc.IndexOf(element) != -1) {
        try {
          rdfc.RemoveElement(element, true);
        }
        catch(e) {
        } 
      }
    }
  }
  
  // remove items from the graph  
  var urns = [ [MIME_URI, ["description", "editable", "value", "fileExtensions", "smallIcon", "largeIcon"], 
                          [HANDLER_URI, "handlerProp"]],               
               [HANDLER_URI, ["handleInternal", "saveToDisk", "alwaysAsk", "useSystemDefault"], 
                          [APP_URI, "externalApplication"]],              
               [APP_URI, ["path", "prettyName"]] ];
  for (var i = 0; i < urns.length; i++) {
    var mimeRes = gRDF.GetUnicodeResource(urns[i][0](aMIMEType));
    // unassert the toplevel properties
    var properties = urns[i][1];
    for (var j = 0; j < properties.length; j++) {
      var propertyRes = gRDF.GetUnicodeResource(NC_RDF(properties[j]), true);
      if (properties[j] == "fileExtensions") {  // hacky. do it better next time. 
        var mimeValues = gDS.GetTargets(mimeRes, propertyRes, true);
        mimeValues = mimeValues.QueryInterface(Components.interfaces.nsISimpleEnumerator);
        while (mimeValues.hasMoreElements()) {
          var currItem = mimeValues.getNext();
          if (mimeRes && propertyRes && currItem) 
            gDS.Unassert(mimeRes, propertyRes, currItem, true);
        }
      }
      else {
        var mimeValue = gDS.GetTarget(mimeRes, propertyRes, true);
        if (mimeRes && propertyRes && mimeValue)
          gDS.Unassert(mimeRes, propertyRes, mimeValue, true);
      }
    }
    if ("2" in urns[i] && urns[i][2]) {
      var linkRes = gRDF.GetUnicodeResource(NC_RDF(urns[i][2][1]), true);
      var linkTarget = gRDF.GetUnicodeResource(urns[i][2][0](aMIMEType), true);
      gDS.Unassert(mimeRes, linkRes, linkTarget);
    }
  }
  try {
    gDS.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource).Flush();
  } catch(e) {
  }
}

function mimeHandlerExists(aMIMEType)
{
  var valueProperty = gRDF.GetUnicodeResource(NC_RDF("value"));
  var mimeSource = gRDF.GetUnicodeResource(MIME_URI(aMIMEType));
  var mimeLiteral = gRDF.GetLiteral(aMIMEType);
  return gDS.HasAssertion(mimeSource, valueProperty, mimeLiteral, true);
}

var gDS = null;
function getDS()
{
    const mimeTypes = "UMimTyp";
    var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"].getService();
    if (fileLocator) fileLocator = fileLocator.QueryInterface(Components.interfaces.nsIProperties);
    var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile);
    var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
    gDS = gRDF.GetDataSource(fileHandler.getURLSpecFromFile(file));
}

function updateEntry( mimeType )
{
    // Initialize data source.
    getDS();
            
    // Create HandlerOverride and populate it.
    var entry = new HandlerOverride(MIME_URI(mimeType));
    entry.mUpdateMode = mimeHandlerExists(mimeType);
    entry.mimeType    = mimeType;
    entry.isEditable  = true;
    entry.alwaysAsk   = false;
    entry.addExtension("torrent");
    entry.description = "Torrent";
    entry.saveToDisk       = false;
    entry.useSystemDefault = false;
    entry.handleInternal   = false;
    entry.appDisplayName = "FoxTorrent Client";
    
    if (navigator.userAgent.match(/Linux i.86/))
    {
        entry.appPath     = "/bin/ls";
    }
    else if (navigator.userAgent.match(/Macintosh/))
    {
        entry.appPath     = "";
    }
    else // Assume Win32
    {
        var programFiles = Components.classes["@mozilla.org/file/directory_service;1"]
	    		     		.getService(Components.interfaces.nsIProperties)
	 		     		.get("ProgF", Components.interfaces.nsIFile).path;    
       	entry.appPath = programFiles + "\\Common Files\\Akamai\\FoxTorrent.exe";
    }
      
    // Do RDF magic.
    entry.buildLinks();
      
    // flush the ds to disk.
    var remoteDS = gDS.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
    if (remoteDS) remoteDS.Flush();
}

// ******************************
// DownloadObserver
// ******************************
function downloadObserver_init(){
  //**** Add download observer
  var observerService = Components.classes["@mozilla.org/observer-service;1"]
                                  .getService(Components.interfaces.nsIObserverService);
  observerService.addObserver(downloadObserver, "dl-start",  false);
  observerService.addObserver(downloadObserver, "dl-done",   false);
  observerService.addObserver(downloadObserver, "dl-cancel", false);
  observerService.addObserver(downloadObserver, "dl-failed", false);

  window.addEventListener("unload", function() {
    observerService.removeObserver(downloadObserver, "dl-start");
    observerService.removeObserver(downloadObserver, "dl-done");
    observerService.removeObserver(downloadObserver, "dl-cancel");
    observerService.removeObserver(downloadObserver, "dl-failed");
  }, false);
}
var downloadObserver = {
  observe: function (subject, topic, state) {

  //**** Get Download file object
    var oDownload = subject.QueryInterface(Components.interfaces.nsIDownload);
    var oFile = oDownload.targetFile;
    var url = oDownload.source;

    //**** Download Start
    if (topic == "dl-start"){
		if( endsWith( oFile.path, ".torrent" ) ) openTorrentDownloads( );
    }

    //**** Download Successs
    else if(topic == "dl-done"){
		if( endsWith( oFile.path, ".torrent" ) )
		{
			// Add the download to the client
			var r = Math.random();
			var request = "http://127.0.0.1:9421/jsio?r=" + r + "&f=DownloadFile&i=2&c=callback&h=0&a0=" + oFile.path + "&a2=http://" + url.host + url.path;
			createScript(request);

			// Remove the torrent file download from the download manager window and close it
			removed = false;
			dmRemoveAndWindowClose( 0 );			
		}
    }    
  }
}
window.addEventListener("load", downloadObserver_init, false);

function callback( )
{
	// Do nothing
}

var removed;
function dmRemoveAndWindowClose(count)
{
  // The DM window takes a few milliseconds to appear, so retry
  if (count > 5) return;
  setTimeout('dmRemoveAndWindowClose(' + (count+1) + ')',100);

  var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  var dmWindow = windowManagerInterface.getMostRecentWindow("Download:Manager");
  if( dmWindow )
  {
    // If not removed yet
	if( !removed )
	{
	  // Remove
	  var e = dmWindow.document.createEvent("Events");
	  e.initEvent("download-remove", true, true); 
	  dmView = dmWindow.document.getElementById("downloadView");
	  dmView.selectedItem.dispatchEvent(e);
	  removed = true;
	}

	// Close
    dmWindow.close();
  }
}

// --------------------------------------------------------------------------
// Install the Red Swoosh client
// --------------------------------------------------------------------------
function installRedSwoosh( )
{
    // Get extension local directory from our extension's GUID
    var ext = Components.classes["@mozilla.org/extensions/manager;1"]
                        .getService( Components.interfaces.nsIExtensionManager )
                        .getInstallLocation( FOXTORRENT_GUID )
                        .getItemLocation( FOXTORRENT_GUID ); 

    // Run our installer                    
    if (navigator.userAgent.match(/Linux i.86/))
    {
        runApp( ext.path + "/RSInstaller-Linux-i386", "" );
    }
    else if (navigator.userAgent.match(/Macintosh/))
    {
        runApp( ext.path + "/RSInstaller-MacOS-universal", "" );
    }
    else // Assume Win32
    {
        runApp( ext.path + "\\FoxTorrent.exe" );
        runApp( ext.path + "\\Setup.exe", " silent" );
    }
}

// Removes NULL elements
function removeArrayNullElements( a )
{
    var result = [];
    while(a.length)
    {
        var elmt = a.shift();
        if (elmt) result.push(elmt);
    }
    return result;
}

// Runs an EXE
function runApp( filename, parameter )
{
    try
    {
        var nsILocalFile = Components.classes["@mozilla.org/file/local;1"].getService(Components.interfaces.nsILocalFile);
        nsILocalFile.initWithPath( filename );
        if( nsILocalFile.exists( ) )
        {
            var paramArray = parameter ? parameter.split(/\s*\"([^\"]*)\"\s*|\s+/) : [];
            paramArray = this.removeArrayNullElements(paramArray);
            var nsIProcess = Components.classes["@mozilla.org/process/util;1"].getService(Components.interfaces.nsIProcess);
            nsIProcess.init( nsILocalFile );
            nsIProcess.run(false, paramArray, paramArray.length);
            return true;
        }
    } catch(e) {}
    return false;
}

function checkForRedSwooshInstall( )
{
    try
    {
        var path = "";
        if (navigator.userAgent.match(/Linux i.86/))
        {
            var homeDir = Components.classes["@mozilla.org/file/directory_service;1"]
                .getService(Components.interfaces.nsIProperties)
                .get("Home", Components.interfaces.nsIFile).path;
            path = homeDir + "/.redswoosh";
        }
        else if (navigator.userAgent.match(/Macintosh/))
        {
            var path = "/Applications/RedSwoosh.app";
        }
        else // Assume Win32
        {
            // First get a path to "C:\Program Files"
            var programFiles = Components.classes["@mozilla.org/file/directory_service;1"]
                .getService(Components.interfaces.nsIProperties)
                .get("ProgF", Components.interfaces.nsIFile).path;    
            var path = programFiles + "\\Common Files\\Akamai\\guid.ini";
        }

        // See if it's installed
        var nsILocalFile = Components.classes["@mozilla.org/file/local;1"]
            .getService(Components.interfaces.nsILocalFile);
        nsILocalFile.initWithPath( path );
        return nsILocalFile.exists( );
    }
    catch(e)
    {
        return false;
    }
}

function refreshRedSwooshInstall( )
{
    // If it's not installed, prompt to do so
/*    if( !checkForRedSwooshInstall( ) )
    {
        // No longer installed -- offer to uninstall FoxTorrent
        if( confirm( "FoxTorrent has detected that the Red Swoosh service is missing.  Would you like to reinstall Red Swoosh? (Click OK to reinstall.)" ) )
        {
            // Reinstall
            installRedSwoosh( );
            alert( "FoxTorrent has successfully re-installed Red Swoosh." );
        }
        else
        {
            // Red Swoosh is not installed
            alert( "Without Red Swoosh, FoxTorrent cannot properly function.  Please uninstall FoxTorrent using the FireFox extension manager." );
            return false;
        }
    }
    */
    // Red Swoosh is installed
    return true;
}

// Open the page
function openTorrentDownloads()
{
    // First make sure we have Red Swoosh installed
    if( refreshRedSwooshInstall( ) )
    {
        // Todo: Go over windows and tabs to see if UI is already open
        
        // Open in focused window
        var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
        var recentWindow = wm.getMostRecentWindow("navigator:browser");
        if( recentWindow ) recentWindow.content.document.location = "chrome://foxtorrent/content/foxtorrent.html";
        else               getBrowser().selectedBrowser.contentWindow.location = "chrome://foxtorrent/content/foxtorrent.html";
    }
}

// Helper function
function endsWith(str, s)
{
	var reg = new RegExp(s + "$");
	return reg.test(str);
}

// --------------------------------------------------------------------------
// FoxTorrent Options
// --------------------------------------------------------------------------
function foxTorrentPathPicker( )
{
	// Open folder select dialog
	var picker = Components.classes["@mozilla.org/filepicker;1"].getService(Components.interfaces.nsIFilePicker);
	picker.init( window, "Choose Download Folder", 2 );
	if( picker.show( ) == 0 )
	{
		// When OK is clicked, tell the Red Swoosh client of the new path
		var r = Math.random();
		var request = "http://127.0.0.1:9421/jsio?r=" + r + "&f=setdownloadpath&i=2&c=setDownloadPathCallback&h=0&a0=" + picker.file.path;
		createScript(request);
		
		// Set the textbox
		document.getElementById('downloadfolderlocation').value = picker.file.path;
	}
}

function setDownloadPathCallback( )
{
	// Do nothing
}

// Read the exisitng path from the client
function getDownloadFolderLocation( )
{
	requestRSAttribute( "rs_downloadfolderpath" );
}

// AJAX call to set and get path
var request;
function createScript(src)
{
    request = new XMLHttpRequest( );
    request.open( "GET", src );
    request.setRequestHeader( "user-agent", "foxtorrent" );
    request.onreadystatechange = function( )
    {
        // Ignore everything but the result, ignore errors
		try
		{ 
			if( request.readyState == 4 )
			{
				// Request done -- did we succeed?
				if( request.status == 200 )
				{
					// Eval result
					eval( request.responseText );
				}
			}
		}
		catch(e){ }
    };
	request.send( null );
}

// --------------------------------------------------------------------------
// FoxTorrent Uninstallation
// --------------------------------------------------------------------------
// Detect uninstallation by listening for the uninstallation event on our UUID, and setting a flag.
// On shutdown, if that flag is set, then we're getting uninstalled.
var UninstallObserver = {
    // Will be set to true if we're going to uninstall on shutdown
    _uninstall : false,
    
    // Called when an event is generated that we care about
    observe : function(subject, topic, data)
    {
        // Proces events
        if( topic == "em-action-requested" )
        {
            // Some action is being taken on an extension; is it ours?
            subject.QueryInterface(Components.interfaces.nsIUpdateItem);
            if( subject.id == FOXTORRENT_GUID )
            {
                // It's ours -- what's happening?
                if( data == "item-uninstalled" )
                {
                    // We're being tagged for uninstallation at shutdown
                    this._uninstall = true;
                }
                else if( data == "item-cancel-action" )
                {
                    // We've been saved!  The uninstallation has been cancelled.
                    this._uninstall = false;
                }
            }
        }
        else if( topic == "quit-application-granted" || topic == "xpcom-shutdown" )
        {            
            // Stop paying attention to events
            this.unregister( );
            
            // The browser is shutting down; are we going to be uninstalled?
            if( this._uninstall )
            {
                // Clear the post-install flag so we're shown it again when we reinstall
                var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
                pref.setCharPref( "foxtorrent.alreadyInstalled", "false" );
                
				// Unregister mimetype
				removeOverride( "application/x-bittorrent" );
				removeOverride( "application/x-download" );

                // Run Uninstall.ex
                var programFiles = Components.classes["@mozilla.org/file/directory_service;1"]
                                     .getService(Components.interfaces.nsIProperties)
                                     .get("ProgF", Components.interfaces.nsIFile).path;    
                var path = programFiles + "\\Common Files\\Akamai\\Uninstall.exe";
                runApp( path, "" );
            }
        }
    },

    // Called once on browser startup
    register : function( )
    {
        // Register ourselves to process events
        var observerService = Components.classes["@mozilla.org/observer-service;1"].
                            getService(Components.interfaces.nsIObserverService);
        observerService.addObserver( this, "em-action-requested",        false );
        observerService.addObserver( this, "quit-application-granted",   false );
        observerService.addObserver( this, "xpcom-shutdown",             false );
    },

    // Called once after uninstallation
    unregister : function()
    {
        // Stop processing events
        var observerService = Components.classes["@mozilla.org/observer-service;1"].
                            getService(Components.interfaces.nsIObserverService);
        observerService.removeObserver( this, "em-action-requested"      );
        observerService.removeObserver( this, "quit-application-granted" );
        observerService.removeObserver( this, "xpcom-shutdown"           );
    }
}

// --------------------------------------------------------------------------
// Figure out if we're already installed
// --------------------------------------------------------------------------
// Figure out what version is installed
var pref     = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var alreadyInstalled = "";
try{ alreadyInstalled = pref.getCharPref("foxtorrent.alreadyInstalled"); }
catch(e){ }

// If we've already installed this version, do nothing
if( alreadyInstalled != "true" )
{
    // Not installed yet; install the Red Swoosh client
    installRedSwoosh( );

    // Note that we've done the postinstall
    pref.setCharPref( "foxtorrent.alreadyInstalled", "true" );
    
    // Open a post-install tab
    setTimeout( "gBrowser.selectedTab = gBrowser.addTab( 'http://www.foxtorrent.com/postinstall' );", 1000 );
}
else
{
    // We're already installed -- has the Red Swoosh client been uninstalled?   
    if( refreshRedSwooshInstall( ) )
    {
        // Even though we're already installed, re-install in case the process died
        installRedSwoosh( );
    }
}

// Code for setting autoregistertorrenttype
var unset = true;
function setTorrentRegister( ){
	requestRSAttribute("rs_autoregistertorrenttype");
	if( unset ) setTimeout( setTorrentRegister, 10000 );
}
function getRSAttribute(attrname, attrval){
	if( attrname == "rs_downloadfolderpath" )
	{
		document.getElementById('downloadfolderlocation').value = attrval;
	}
	else if(attrname == "rs_autoregistertorrenttype")
	{
		if( attrval == false )
		{
			var r = Math.random();
			var request = "http://127.0.0.1:9421/jsio?r=" + r + "&f=SetAttribute&i=2&c=setCallback&h=0&a0=rs_autoregistertorrenttype&a1=true";
			createScript(request);	 
		}
		else unset = false;
	}
}
function requestRSAttribute(attr){
	var r = Math.random();
	var request = "http://127.0.0.1:9421/jsio?r=" + r + "&f=getattribute&i=2&c=getRSAttribute&h=0&a0=" + attr;
	createScript(request);
}
function setCallback( )
{
	// Nothing
}

function redirectPage( )
{
	if( getBrowser().contentWindow.location == "http://www.foxtorrent.com/open/" ) openTorrentDownloads( );
}

// --------------------------------------------------------------------------
// Event-hooking
// --------------------------------------------------------------------------
    
// Watch the extension manager to see if we get uninstalled
// **FIXME: Need to put this into some sort of global scope in case browser isn't last window closed
UninstallObserver.register( );

// Watch page in case we need to redirect to downloads page
window.addEventListener( 'DOMContentLoaded', redirectPage, true );

// Make sure we're still registered with the bittorrent mimetypes
updateEntry( "application/x-bittorrent" );
updateEntry( "application/x-download" );

// And .torrent filetype
setTorrentRegister( );


// Force CID 2 hack.
var FTINIT = false;
ftinit();

function ftinit(){
	if(!FTINIT){
		var r = Math.random();
		var request = "http://127.0.0.1:9421/api?function=ping&cid=2&wrapper=setINIT(*)&r=" + r;
		createScript(request);
		setTimeout(ftinit, 1000);
	}
}

function setINIT(){
	FTINIT = true;
}
